/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.frame.pm.utils.PmDataDictUtils;
import com.thinkgem.jeesite.modules.sys.entity.SysOffice;
import com.thinkgem.jeesite.modules.sys.entity.SysUser;
import com.thinkgem.jeesite.modules.sys.service.SysOfficeService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 机构Controller
 *
 * @author kongxiangsheng
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/sysOffice")
public class SysOfficeController extends BaseController {
    @Autowired
    private SysOfficeService sysOfficeService;

    @RequiresPermissions("sys:sysOffice:view")
    @RequestMapping(value = {""})
    public String index(SysOffice sysOffice, Model model) {
//        model.addAttribute("list", officeService.findAll());
        return "modules/sys/SysOffice/index";
    }

    @RequiresPermissions("sys:sysOffice:view")
    @RequestMapping(value = {"list"})
    public String list(SysOffice sysOffice, Model model) {
        String officeId = "";
        if (StringUtils.isBlank(sysOffice.getId())) {
            SysUser user = UserUtils.getUser();
            officeId = user.getCompanyId();
        } else {
            officeId = sysOffice.getId();
        }

        model.addAttribute("office", sysOffice);
        model.addAttribute("list", sysOfficeService.selectWithChildren(officeId));
        return "modules/sys/SysOffice/list";
    }

    @RequiresPermissions("sys:sysOffice:view")
    @RequestMapping(value = "form")
    public String form(SysOffice sysOffice, Model model) {
        SysUser user = UserUtils.getUser();
        SysOffice userOffice = UserUtils.getOffice(user.getOfficeId());
        if (StringUtils.isNotBlank(sysOffice.getId())) {
            sysOffice = sysOfficeService.getById(sysOffice.getId());
        }
        if (StringUtils.isBlank(sysOffice.getParentId())) {
            sysOffice.setParentId(user.getCompanyId());
        }
        if (sysOffice.getAreaId() == null) {
            sysOffice.setAreaId(userOffice.getAreaId());
        }
        // 自动获取排序号
        if (StringUtils.isBlank(sysOffice.getId()) && StringUtils.isNotBlank(sysOffice.getParentId())) {
            int size = 0;
            List<SysOffice> list = sysOfficeService.selectAll();
            for (int i = 0; i < list.size(); i++) {
                SysOffice e = list.get(i);
                if (StringUtils.isNotBlank(e.getParentId()) && e.getParentId().equals(sysOffice.getParentId())) {
                    size++;
                }
            }

            SysOffice parentOffice = sysOfficeService.getById(sysOffice.getParentId());
            sysOffice.setCode(parentOffice.getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size + 1 : 1), 3, "0"));
        }
        model.addAttribute("sysOffice", sysOffice);
        return "modules/sys/SysOffice/form";
    }

    @RequiresPermissions("sys:sysOffice:edit")
    @RequestMapping(value = "save")
    public String save(SysOffice sysOffice, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, sysOffice)) {
            return form(sysOffice, model);
        }
        sysOfficeService.checkAndSave(sysOffice);

        if (sysOffice.getChildDeptList() != null) {
            SysOffice childOffice = null;
            for (String id : sysOffice.getChildDeptList()) {
                childOffice = new SysOffice();
                childOffice.setName(PmDataDictUtils.getDataDictValue("sys_office_common", id, "未知"));
                childOffice.setParentId(sysOffice.getId());
                childOffice.setAreaId(sysOffice.getAreaId());
                childOffice.setType("2");
                childOffice.setGrade(sysOffice.getGrade() + 1);
                childOffice.setUseable(BaseConstants.YES_NO_FLAG_Y);
                sysOfficeService.checkAndSave(childOffice);
            }
        }

        addMessage(redirectAttributes, "保存机构'" + sysOffice.getName() + "'成功");
        String id = "0".equals(sysOffice.getParentId()) ? "" : sysOffice.getParentId();
        return "redirect:" + adminPath + "/sys/sysOffice/list?id=" + id + "&parentIds=" + sysOffice.getParentIds();
    }

    @RequiresPermissions("sys:sysOffice:edit")
    @RequestMapping(value = "delete")
    public String delete(SysOffice sysOffice, RedirectAttributes redirectAttributes) {
        sysOfficeService.removeById(sysOffice);
        addMessage(redirectAttributes, "删除机构成功");
        return "redirect:" + adminPath + "/sys/sysOffice/list?id=" + sysOffice.getParentId() + "&parentIds=" + sysOffice.getParentIds();
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeValue")
    public String treeValue(@RequestParam(required = true) String id, HttpServletResponse response) {
        String officeName = "";
        SysOffice sysOffice = sysOfficeService.getById(id);
        if (null != sysOffice) {
            officeName = sysOffice.getName();
        }
        return officeName;
    }

    /**
     * 获取机构JSON数据。
     *
     * @param extId    排除的ID
     * @param type     类型（1：机构；2：部门/小组/其它：3：用户）
     * @param grade    显示级别
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, @RequestParam(required = false) String type,
                                              @RequestParam(required = false) Long grade, @RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<SysOffice> list = sysOfficeService.findList(isAll);
        for (int i = 0; i < list.size(); i++) {
            SysOffice e = list.get(i);

            // 排除额外编号Id
            if (StringUtils.isNotBlank(extId)) {
                if (extId.equals(e.getId()) || e.getParentIds().indexOf("," + extId + ",") == -1) {
                    continue;
                }
            }

            // 是否只展示公司
            if (StringUtils.isNotBlank(type)) {
                if (!type.equals(e.getType())) {
                    continue;
                }
            }
            // 排除指定等级以下的机构
            if (null != grade && e.getGrade() > grade.intValue()) {
                continue;
            }
            // 排除不可用的机构
            if (!BaseConstants.YES_NO_FLAG_Y.equals(e.getUseable())) {
                continue;
            }

            // 剩下的都要统计
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getParentId());
            map.put("pIds", e.getParentIds());
            map.put("name", e.getName());
            if (type != null && "3".equals(type)) {
                map.put("isParent", true);
            }
            mapList.add(map);
        }
        return mapList;
    }
}
